package com.tcdp.daos;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.ParameterExpression;
import javax.persistence.criteria.Root;

import com.tcdp.models.GalleryImage;

public class GalleryImageDao extends AbstractDao {

	public GalleryImage findById(int id){
		GalleryImage image = em.find(GalleryImage.class, id);
		return image;
	}
	
	public GalleryImage findByUrl(String url){
		GalleryImage galleryImage = null;
		
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<GalleryImage> cq = cb.createQuery(GalleryImage.class);
		Root<GalleryImage> root = cq.from(GalleryImage.class);
		cq.select(root).where(cb.equal(root.<String>get("galleryImageUrl"), url));
		TypedQuery<GalleryImage> tq = em.createQuery(cq);
		try{
			galleryImage = tq.getSingleResult();
		}catch(NoResultException e){
			throw404(e);
		}
		
		return galleryImage;
	}
	
	public String findIdByUrl(String url){
		String id = null;
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Tuple> cq = cb.createTupleQuery();
		Root<GalleryImage> root = cq.from(GalleryImage.class);
		ParameterExpression<String> nameParameter = cb.parameter(String.class,
				"imgUrl");
		cq.multiselect(root.get("galleryImageId")).where(cb.equal(root.<String>get("galleryImageUrl"),nameParameter));
		TypedQuery<Tuple> tq = em.createQuery(cq);
		tq.setParameter("imgUrl", url);
		List<Tuple> tupleResult = tq.getResultList();
		for (Tuple t : tupleResult) {
			id = t.get(0).toString();
		}
		
		return id;
	}
	
}
